package com.sc.controller;

import com.github.pagehelper.PageInfo;
import com.sc.pojo.Class;
import com.sc.pojo.User;
import com.sc.service.ClassService;
import com.sc.service.UserService;
import com.sc.util.CodeUtil;
import com.sc.util.MD5;
import com.sc.util.UploadDownloadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService us;
    @Autowired
    ClassService cs;
    @RequestMapping("/login")
    public String login(User a, HttpSession session, String captcha, Map m) {
        String ran = (String) session.getAttribute("randomCode");
        if (ran.equalsIgnoreCase(captcha)) {
            //密码加密
            a.setPassword(MD5.MD5Code(a.getPassword()));
            User u = us.login(a);
            if (u != null) {
                if (u.getStatus() == 0) {
                m.put("error", "该用户已被封禁！");
                } else {
                    session.setAttribute("theUser", u);
                    return "forward:/toHome";
                }
            } else m.put("error", "账号密码错误!");
        } else m.put("error","验证码错误!");
        return "forward:/toLogin";
    }
    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        CodeUtil.processRequest(req,response);
    }

    @RequestMapping(value = "/checkUser", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String checkUser(String account) {
        if (us.checkUser(account)) return "该账号已存在!";
        return "账号可以使用！";
    }

    @RequestMapping(value = "/checkTeacher", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String checkTeacher(Integer classid) {
        System.out.println("进入比较");
        if (classid!=1){
            if (us.checkTeacher(classid)) return "该班级已有老师!";
        }
        return "该班级可以选择！";
    }

    @RequestMapping("/add")
    public String add(User u, MultipartFile myHead,HttpServletRequest req,HttpSession session) {
        if (myHead.getOriginalFilename().length() > 0) {
            u.setHeadpic(UploadDownloadUtil.upload(req, myHead));
        }
        u.setPassword(MD5.MD5Code(u.getPassword()));
        if (u.getRoleid() == 2) {
            User user = us.queryByCid(u.getClassid());
            Class c = cs.queryById(u.getClassid());
            c.setTid(user.getId());
            cs.upd(c);
        }
        us.add(u);
        return "redirect:/user/show?type="+u.getRoleid();
    }
    @RequestMapping("/register")
    public String register(User u, MultipartFile myHead,HttpServletRequest req) {
        if (myHead.getOriginalFilename().length() > 0) {
            u.setHeadpic(UploadDownloadUtil.upload(req, myHead));
        }
        u.setPassword(MD5.MD5Code(u.getPassword()));
        us.add(u);
        return "redirect:/login.jsp";
    }
    @RequestMapping("/del")
    public String del(Integer id, Integer roleid, String headpic, HttpServletRequest req) {
        us.del(id);
        String path = req.getServletContext().getRealPath("/upload") + File.separator + headpic;
        File f = new File(path);
        f.delete();
        return "redirect:/user/show?type="+roleid;
    }

    @RequestMapping("/update")
    public String update(User u, MultipartFile myHead, HttpServletRequest req) {
        User user = us.selectById(u.getId());
        if (myHead.getOriginalFilename().length() > 0) {
            String path = req.getServletContext().getRealPath("/upload") + File.separator + u.getHeadpic();
            File f = new File(path);
            f.delete();
            u.setHeadpic(UploadDownloadUtil.upload(req, myHead));
        }
        //如果未改动密码 将之设为空 如果改动 进行加密
        if (u.getPassword().equals(user.getPassword())) {
            u.setPassword(null);
        } else {
            u.setPassword(MD5.MD5Code(u.getPassword()));
        }

        if (u.getClassid() != null && u.getClassid() == -1) u.setClassid(null);
        if (u.getRoleid() == 2) {
            Class c1 = cs.queryByTid(u.getId());
            if (c1 != null) {
                c1.setTid(null);
                cs.upd(c1);
            }
            Class c = cs.queryById(u.getClassid());
            if (c != null) {
                c.setTid(u.getId());
                cs.upd(c);
            }
        }
        us.upd(u);
        return "redirect:/user/show?type=" + u.getRoleid();
    }

    @RequestMapping("/show")
    public String show(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "4") Integer pageSize, Integer type, String keyword, Map m) {
        PageInfo<User> p = us.show(pageNum, pageSize,type,keyword);
        m.put("p",p);
        m.put("keyword",keyword);
        if (type==1){
            return "/admin/user/admin/list";
        } else if (type == 2) {
            return "/admin/user/teacher/list";
        } else if (type == 3){
            return "/admin/user/student/list";
        } else {
            return null;
        }
    }

    //批量改动部分
    @RequestMapping("/delAll")
    public String delAll(Integer[] id,HttpServletRequest req, Integer type) {
        if (id != null) {
            List<String> list = us.delAll(id);
            String path = req.getServletContext().getRealPath("/upload") + File.separator;
            for (String s:list) {
                new File(path+s).delete();
            }
        }
        return "redirect:/user/show?type="+type;
    }

    @RequestMapping("/change")
    public String change(Integer[] id, String tag, Integer type) {
        if (id != null) {
            if ("open".equals(tag)) {
                us.openAll(id);
            } else if ("close".equals(tag)) {
                us.closeAll(id);
            }
        }
        return "redirect:/user/show?type="+type;
    }

    @RequestMapping("/toIndex")
    public String toIndex() {
        return "/admin/index";
    }
    @RequestMapping("/toAdd")
    public String toAdd(Integer newType, Map m) {
        m.put("classList",cs.queryAll());
        if (newType == 1) {
            return "/admin/user/admin/add";
        } else if (newType == 2) {
            return "/admin/user/teacher/add";
        } else if (newType == 3) {
            return "/admin/user/student/add";
        } else {
            return null;
        }
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Integer roleid, Integer id, Map m) {
        m.put("classList",cs.queryAll());
        m.put("upd",us.selectById(id));
        if (roleid == 1) {
            return "/admin/user/admin/edit";
        } else if (roleid == 2) {
            return "/admin/user/teacher/edit";
        } else if (roleid == 3) {
            return "/admin/user/student/edit";
        } else {
            return null;
        }
    }

    @RequestMapping("/editPwd")
    public String editPwd(HttpSession session, String oldpwd, String password, Map m) {
        User u = (User) session.getAttribute("theUser");
        String pw = u.getPassword();
        if (pw.equals(MD5.MD5Code(oldpwd))) {
            u.setPassword(password);
            us.upd(u);
            return "redirect:/user/toAdmin";
        } else {
            m.put("error","原密码输入错误");
        }
        return "/admin/editPwd";
    }

    @RequestMapping("/profile")
    public String profile(User u,HttpSession session,MultipartFile myHead,HttpServletRequest req) {
        if (myHead.getOriginalFilename().length() > 0) {
            String path = req.getServletContext().getRealPath("/upload") + File.separator + u.getHeadpic();
            File f = new File(path);
            f.delete();
            u.setHeadpic(UploadDownloadUtil.upload(req, myHead));
        }
        us.upd(u);
        session.setAttribute("theUser",u);
        return "redirect:/user/toAdmin";
    }
    @RequestMapping("/toAdmin")
    public String toAdmin() { return "/admin/home";}
    @RequestMapping("/toeditPwd")
    public String toeditPwd() {
        return "/admin/editPwd";
    }
    @RequestMapping("/toprofile")
    public String toprofile() {
        return "/admin/profile";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("theUser");
        return "redirect:/toLogin";
    }
}
